package com.nowcoder.controller.interceptor;

import com.nowcoder.entity.LoginTicket;
import com.nowcoder.entity.User;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.CookiesUtil;
import com.nowcoder.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    // 请求打入前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookiesUtil.getValue(request, "ticket");
        if(ticket != null) {
            // 查询ticket
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            if(loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                User user = userService.findUserById(loginTicket.getUserId());
                // 本次请求存储user
                HostHolder.setUser(user);
            }
        }
        return true;
    }

    // 渲染前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = HostHolder.getUser();
        System.out.println(request.getRequestURI() + " " + user);
        if(user != null && modelAndView != null) {
            modelAndView.addObject("loginUser", user);
        }
    }
}
